package com.yuxi.al.arraymerge;

/**
 * 两个有序数组合并
 * Created by yuxi on 2017/8/27.
 */
public class SortArrayMerge {
    public static void main(String[] args) {
        int[] arr1 = {1, 3, 5, 7, 9};
        int[] arr2 = {12, 13, 14, 15, 16, 17};
        int[] arr3 = mergeArray(arr1, arr2);

        for (int i = 0; i < arr3.length; i++) {
            System.out.print(arr3[i]+"--");
        }
    }

    private static int[] mergeArray(int[] arr1, int[] arr2) {
        if (arr1.length < 0 && arr2.length < 0) {
            return null;
        }

        int length1 = arr1.length;
        int length2 = arr2.length;
        int[] res = new int[length1 + length2];
        int i = 0;
        int j = 0;
        int k = 0;
        while (i < length1 && j < length2) {
            if (arr1[i] < arr2[j]) {
                res[k++] = arr1[i++];
            } else {
                res[k++] = arr2[j++];
            }
        }
        if (i < length1) {
            for (int m = i; m < length1; m++) {
                res[k++] = arr1[m];
            }
        }
        if (j < length2) {
            for (int m = j; m < length2; m++) {
                res[k++] = arr2[m];
            }
        }
        return res;
    }
}
